/*
 * Copyright (C) 2004-2006 nickyb@users.sourceforge.net
 * 
 * This file is part of FreeQueryBuilder (http://querybuilder.sourceforge.net)
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package net.sourceforge.querybuilder;

import java.awt.Color;
import java.awt.GridLayout;

import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.JCheckBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.UIManager;

import javax.swing.event.InternalFrameEvent;

public class DiagramEntity extends JInternalFrame
{
	private JLabel header;
	private JPanel fields;
	
	private Vector fieldsDisplaySize = new Vector();
	
	Vector selectedFields = new Vector();
	Vector joinedFields	= new Vector();
	
	QueryTokens.Table querytoken;

	static Color BGCOLOR_JOINED = new Color(225,235,224);
	static Color BGCOLOR_DEFAULT = Color.white;
	static Color BGCOLOR_SELECTED = UIManager.getColor("Table.selectionBackground");
	static Color BGCOLOR_START_JOIN = new Color(255,230,230);
	
	public DiagramEntity(QueryTokens.Table table)
	{
		super(table.getName(), false, true);
		querytoken = table;
		
		setLayer(QueryDiagram.PALETTE_LAYER);
		putClientProperty("JInternalFrame.isPalette", Boolean.TRUE);
		
		BasePanel content = new BasePanel();
		content.setComponentNorth(header = new JLabel(querytoken.getAlias()));
		content.setComponentCenter(fields = new JPanel(new GridLayout(0,1,0,0)));

		getContentPane().add(content);
	}
	
	public void setEnabled(boolean b)
	{
		super.setEnabled(b);
		header.setEnabled(b);
	}

	public String getHeader()
	{
		return header.getText();
	}
	
	Field addField(String label, boolean key, int displaySize, String infos)
	{
		String tooltip = label;
		if(infos!=null) tooltip = label + " [ " + infos + " ]";
		
		Field field = new Field(querytoken,label,key);
		field.setToolTipText(tooltip);
		
		field.addMouseListener(new ClickHandler());
		field.setBackground(DiagramEntity.BGCOLOR_DEFAULT);
		field.setEnabled(false);
		field.setBorder(null);
		
		if(displaySize == 0) displaySize = 10;
			
		fieldsDisplaySize.addElement(new Integer(displaySize));
		fields.add(field);
		
		return field;
	}
	
	public int findFieldPosition(String label)
	{
		for(int i=0; i<fields.getComponentCount(); i++)
		{
			Field field = (Field)fields.getComponent(i);
			if(field.getText().equals(label)) return i;
		}
		
		return -1;		
	}
	
	Field getField(String label)
	{
		int index = findFieldPosition(label);
		return index!=-1?(Field)fields.getComponent(index):null;
	}
	
	QueryDiagram getQueryDiagram()
	{
		return (QueryDiagram)this.getDesktopPane();
	}
	
	QueryBuilder getQueryBuilder()
	{
		return getQueryDiagram().builder;
	}
	
	protected void fireInternalFrameEvent(int id)
	{
		if(id == InternalFrameEvent.INTERNAL_FRAME_CLOSING)
		{
			for(int i=0; i<fields.getComponentCount(); i++)
			{
				Field field = (Field)fields.getComponent(i);
				
				this.getQueryBuilder().listbar.removeItem(field.querytoken.toString(false,false));
				this.getQueryBuilder().clauses.removeColumn(field.querytoken.toString(QueryBuilder.useIdentifierQuote,false));
			}
			
			this.getQueryDiagram().removeAllRelation(this);
			this.getQueryBuilder().syntax.refresh();			
		}
		
		super.fireInternalFrameEvent(id);
	}
	
	void workModeChanged()
	{
		for(int i=0; i<fields.getComponentCount(); i++)
		{
			fields.getComponent(i).setBackground(BGCOLOR_DEFAULT);
		}
		
		Color higlightColor = this.getQueryBuilder().isJoinMode() ?  BGCOLOR_JOINED : BGCOLOR_SELECTED;
		Vector higlights	= this.getQueryBuilder().isJoinMode() ? joinedFields : selectedFields;
		
		for(int i=0; i<higlights.size(); i++)
			((Field)higlights.elementAt(i)).setBackground(higlightColor);
	}

	void joined(Field column)
	{
		if(this.getQueryBuilder().isJoinMode())
			column.setBackground(BGCOLOR_JOINED);
		
		joinedFields.addElement(column);
	}

	void unjoined(Field column)
	{
		joinedFields.removeElement(column);
		column.setBackground(BGCOLOR_DEFAULT);
		
		if(this.getQueryBuilder().isJoinMode())
		{
			if(joinedFields.contains(column))
				column.setBackground(BGCOLOR_JOINED);
		}
		else if(selectedFields.contains(column))
			column.setBackground(BGCOLOR_SELECTED);
	}
	
	void setSelectionStatus(String colName, boolean status)
	{
		Field col = getField(colName);
		if(col!=null) setSelectionStatus(col,status);
	}
	
	private void setSelectionStatus(Field field, boolean status)
	{
		if(status)
		{
			if(!selectedFields.contains(field))
			{
				selectedFields.addElement(field);
			
				if(!this.getQueryBuilder().isJoinMode())
					field.setBackground(DiagramEntity.BGCOLOR_SELECTED);
	
				this.getQueryBuilder().listbar.addColumn(field.querytoken);
			}			
		}
		else
		{
			if(selectedFields.contains(field))
			{
				selectedFields.removeElement(field);
			
				if(!this.getQueryBuilder().isJoinMode())
					field.setBackground(DiagramEntity.BGCOLOR_DEFAULT);
					
				this.getQueryBuilder().listbar.removeItem(field.querytoken.toString(false,false));
			}			
		}
	}
	
//	/////////////////////////////////////////////////////////////////////////////
//	Field
//	/////////////////////////////////////////////////////////////////////////////
	public class Field extends JCheckBox
	{
		QueryTokens.Column querytoken;
		
		public Field(QueryTokens.Table owner, String name, boolean iskey)
		{
			this(new QueryTokens.Column(owner, name),iskey);
		}
		
		public Field(QueryTokens.Column querytoken, boolean iskey)
		{
			super(querytoken.getName(),iskey);
			this.querytoken = querytoken;
			this.setOpaque(true);
		}
	}
	
//	/////////////////////////////////////////////////////////////////////////////
//	Highlights
//	/////////////////////////////////////////////////////////////////////////////
	private class ClickHandler extends MouseAdapter
	{
		public void mousePressed(MouseEvent evt)
		{
			if(evt.getModifiers() == MouseEvent.BUTTON3_MASK) return;
			
			Field col = (Field)evt.getSource();
			
			if(DiagramEntity.this.getQueryBuilder().isJoinMode())
				DiagramEntity.this.getQueryDiagram().join(DiagramEntity.this, col);
			else
			{
				if(selectedFields.contains(col))
					DiagramEntity.this.setSelectionStatus(col, false);
				else
					DiagramEntity.this.setSelectionStatus(col, true);
			}
		}
	}
}
